package org.zhangsh.bio;

import org.zhangsh.socket.HostInfo;
import org.zhangsh.socket.InputUtil;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-18
 */
public class BioEchoClient {

    public static void main(String[] args) {

        try {
            Socket client = new Socket(HostInfo.HOST_NAME, HostInfo.HOST_PORT);
            // 客户端的输入，也就是服务端响应的信息
            Scanner scanner = new Scanner(client.getInputStream());
            scanner.useDelimiter("\n");
            // 客户端输出，也就是向服务端发送的信息
            PrintStream out = new PrintStream(client.getOutputStream());

            for(;;){

                String inputData = InputUtil.getInputString("[client]请输入要向服务端发送的信息:");
                System.out.println();
                System.out.println("[client]即将把输入的内容:"+ inputData + " 发送至服务端...");
                // 发送服务端，此处这样发送，不能用println，这样会导致NIOserver时两次发送
                out.print(inputData.trim()+"\n");

                //查看响应
                if(scanner.hasNext()){
                    String serverInfo = scanner.next().trim();
                    System.out.println("[client]服务端响应的信息:" + serverInfo);

                    // 服务器响应byebye，则退出
                    if("byebye".equals(serverInfo)){
                        System.out.println("[client]即将退出");
                        break;
                    }
                }
            }
            out.close();
            scanner.close();
            client.close();
        }catch (IOException e){

        }

    }
}
